package com.uni.servlets;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.IOException;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.context.ApplicationContext;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.uni.db.FileService;
import com.uni.domain.File;

public class FilePuter extends HttpServlet {

	private static final long serialVersionUID = 3751087969712182544L;

	@RequestMapping(method = RequestMethod.GET)    
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
        ApplicationContext context = WebApplicationContextUtils.getWebApplicationContext(getServletContext());
        FileService fileService = (FileService) context.getBean("fileService");
        String sid = request.getParameter("id");
        if (sid != null && !"".equals(sid)) {
            File file = (File)fileService.get(Long.parseLong(sid));
            if(file != null){
            	response.setContentType(file.getContentType());
            	response.setCharacterEncoding("UTF-8");
            	response.setStatus(200);
	            try {
	                BufferedOutputStream out = new BufferedOutputStream(response.getOutputStream());
	                BufferedInputStream in = new BufferedInputStream(new ByteArrayInputStream(file.getData()));
	                int l;
	                byte[] buffer = new byte[1024];
	                while (true) {
	                    l = in.read(buffer);
	                    if (l == -1) break;
	                    out.write(buffer, 0, l);
	                }
	            } catch (IOException e) {
	                e.printStackTrace();
	            }
            } else {
            	response.setStatus(404);
            	return;
            }
        } 
    }

}
